//
//  ViewController.m
//  Gxj
//
//  Created by 刘伟 on 2017/8/29.
//  Copyright © 2017年 wkq. All rights reserved.
//

#import "ViewController.h"
#import "HomeCycleScrollView.h"
#import "HomeNaoBaoFormTableViewCell.h"
#import "HomeYuGaoFromTableViewCell.h"
#import "HomeListFromTableViewCell.h"
#import "GXBannerFromModel.h"
#import "HomeMeetingFromModel.h"
#import "HomeStormFromModel.h"
#import "HomeStormFromModel_Two.h"
#import "EditingideaFromViewController.h"
#import "EditdebateViewController.h"
#import "ReleaseConferenceViewController.h"
#import "HomeDebateFromTableViewCell.h"

#import "HotspotdebateSYViewController.h"//热门辩论
#import "ParticularsViewController.h"
#import "HotDebateSYModel.h"//热门辩论

@interface ViewController ()<UITableViewDelegate ,UITableViewDataSource ,HomeListDelegate>
{
    UIView *_homeHeadView;
    GXBannerFromModel *_gxBannerModel;
    HomeYuGaoFromTableViewCell *_homeYuGaoCell;
    HomeMeetingFromModel *_homeMeetingModel;
    HomeStormFromModel *_stormModel;
    NSMutableArray *_stormDataSource;
    //热门辩论数据数组
    NSMutableArray * _hotDebateSYModelArr;
    NSMutableArray * _hotDebateSYModelArrTwo;
    UIView *_navgationView;
}
//通知点击按钮代理人

@property(nonatomic, strong) HomeCycleScrollView *cycScrollView;//滚动视图
@property(nonatomic, strong) PYSearchViewController *searchViewController;//搜索
@property (nonatomic,strong) UITableView *tableView;

//导航条上拉隐藏下拉显示
@property (nonatomic, assign) CGFloat borderNum;

@end

@implementation ViewController

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //去掉导航栏底部的黑线
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /* 轮播图*/
    [self setUpCycleScrollView];
//    [CYTabBarConfig shared].haveBorder = NO;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;// 去掉所有cell的分割线
    self.tableView.backgroundColor = [UIColor colorWithRed:242.0/255.0 green:242.0/255.0 blue:242.0/255.0 alpha:1];
    [self.view addSubview:self.tableView];
    
    [self getGXbanner];
    [self getHomeYuGaoMeeting];
    [self getHomeStorm];
    //热门辩论
    [self setHotDebateSYModelUp];
}
#pragma mark - 获取首页banner
- (void)getGXbanner
{
    NSDictionary * dicc =@{@"type":@"1"
                           };
    
    [KQNetWork postWithURLString:[NSString stringWithFormat:@"%@/api/banner/index",MAIN_URL] parameters:dicc success:^(NSDictionary *dic){
                          
        _gxBannerModel = [[GXBannerFromModel alloc] initWithDictionary:dic];
        
        [self.cycScrollView setModel:_gxBannerModel];
                          
        } failure:^(NSError *error) {
    }];
}
#pragma mark - 获取首页预告会议
- (void)getHomeYuGaoMeeting
{
    NSString *userid = [KQUserDefaults readUserDataWithKey:@"userid"];
    
    NSDictionary *dict = @{@"userid":userid
                           };
    
    [KQNetWork postWithURLString:[NSString stringWithFormat:@"%@/api/meeting/hotlist",MAIN_URL] parameters:dict success:^(NSDictionary *dic) {
        
        _homeMeetingModel = [[HomeMeetingFromModel alloc] initWithDictionary:dic];
        
        [_homeYuGaoCell setModel:_homeMeetingModel];
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark - 获取首页脑暴
- (void)getHomeStorm
{
    NSString *userid = [KQUserDefaults readUserDataWithKey:@"userid"];
    
    NSDictionary *dicc = @{@"userid":userid,
                           @"type":@"1"
                           };
    [KQNetWork postWithURLString:[NSString stringWithFormat:@"%@/api/think/hotlist",MAIN_URL] parameters:dicc success:^(NSDictionary *dic) {
        
        _stormModel = [[HomeStormFromModel alloc] initWithDictionary:dic];
        
        _stormDataSource = [NSMutableArray array];
        for (HomeStormFromModel_Two *model in _stormModel.list) {
            [_stormDataSource addObject:model];
        }
        
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark - 获取首页热门辩论
- (void)setHotDebateSYModelUp
{
    NSString *userid = [KQUserDefaults readUserDataWithKey:@"userid"];
    
    NSDictionary *dicc = @{@"userid":userid,
                           @"type":@"2",
                           @"page":@"1",
                           @"index":@"2"
                           };
    [KQNetWork postWithURLString:[NSString stringWithFormat:@"%@/api/think/hotlist",MAIN_URL] parameters:dicc success:^(NSDictionary *dic) {
        
        //_debateThestormModel = [[DebateThestormModel alloc] initWithDictionary:dic];
        
        
        _hotDebateSYModelArr = [NSMutableArray array];
        _hotDebateSYModelArrTwo = [NSMutableArray array];
        HotDebateSYModel * model= [[HotDebateSYModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        
        
        
        for (NSDictionary * dicList in model.list)
        {
            HotDebateSYModel_list * modelList =[[HotDebateSYModel_list alloc] init];
            [modelList setValuesForKeysWithDictionary:dicList];
            HotDebateSYModel_list_comment *modelListComment = [[HotDebateSYModel_list_comment alloc] init];
            [modelListComment setValuesForKeysWithDictionary:modelList.comment];
            [_hotDebateSYModelArr addObject:modelList];
            [_hotDebateSYModelArrTwo addObject:modelListComment];
            [self.tableView reloadData];
            
        }
    }
                         failure:^(NSError *error)
     {
         NSLog(@"请求错误");
     }];
}

#pragma mark - 主view滑动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static float lastOffY  = 0;
    float curOffY = scrollView.contentOffset.y;
    
    if (scrollView.frame.size.height >= scrollView.contentSize.height ||     //内容高度低于scrollView高度，不隐藏
        fabs(curOffY)  +UIScreenWidth> scrollView.contentSize.height || //拉至最底部时，不做处理
        curOffY < 0                                                          //拉至最顶部时，不做处理
        )
    {
        return;
    }
    if (curOffY - self.cycScrollView.navigationView.origin.y > 10)
    {
        //向上
        lastOffY = curOffY;
        [self.view addSubview:self.cycScrollView.navigationView];
        self.cycScrollView.navImage.image = [UIImage imageNamed:@"tbg"];
        self.cycScrollView.navigationView.alpha = (curOffY -_borderNum )/_borderNum;
//        [self showTabBar];
    }
    else if(UIScreenHeight -curOffY > UIScreenHeight - 90)
    {
        //向下
        lastOffY = curOffY;
        [self.cycScrollView addSubview:self.cycScrollView.navigationView];
        self.cycScrollView.navImage.image = [UIImage imageNamed:@""];
        self.cycScrollView.navigationView.alpha = (_borderNum -curOffY )/_borderNum;
//        [self hideTabBar];
    }
}

- (void)showTabBar
{
    if (self.tabBarController.tabBar.hidden == NO)
    {
        return;
    }
    
    UIView *contentView;
    if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    
    contentView.frame = CGRectMake(contentView.bounds.origin.x,
                                   contentView.bounds.origin.y,
                                   contentView.bounds.size.width,
                                   contentView.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.4f;
    animation.type = kCATransitionMoveIn;
    animation.subtype = kCATransitionFromTop;
    self.tabBarController.tabBar.hidden = NO;
    [self.tabBarController.tabBar.layer addAnimation:animation forKey:@"animation2"];
    
    CATransition *animation1 = [CATransition animation];
    animation1.duration = 0.4f;
    animation1.type = kCATransitionMoveIn;
    animation1.subtype = kCATransitionFromBottom;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar.layer addAnimation:animation1 forKey:@"animation3"];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bg"]forBarMetrics:UIBarMetricsDefault];
}

- (void)hideTabBar
{
    if (self.tabBarController.tabBar.hidden == YES)
    {
        return;
    }
    UIView *contentView;
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,
                                   contentView.bounds.origin.y,
                                   contentView.bounds.size.width,
                                   contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    
    
    CATransition *animation1 = [CATransition animation];
    animation1.timingFunction=UIViewAnimationCurveEaseInOut;
    animation1.duration = 0.4f;
//    animation1.delegate = self;
    animation1.type = kCATransitionReveal;
    animation1.subtype = kCATransitionFromTop;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar.layer addAnimation:animation1 forKey:@"animation0"];
    
    //定义个转场动画
    CATransition *animation = [CATransition animation];
    //转场动画持续时间
    animation.duration = 0.4f;
    //计时函数，从头到尾的流畅度？？？
    animation.timingFunction=UIViewAnimationCurveEaseInOut;
    //转场动画类型
    animation.type = kCATransitionReveal;
    //转场动画子类型
    animation.subtype = kCATransitionFromBottom;
    //动画时你需要的实现
    self.tabBarController.tabBar.hidden = YES;
    //添加动画 （转场动画是添加在层上的动画）
    [self.tabBarController.tabBar.layer addAnimation:animation forKey:@"animation1"];
}

#pragma mark - 轮播图
- (void)setUpCycleScrollView {
    //轮播图的位置显示
    self.cycScrollView = [[HomeCycleScrollView alloc ] initWithFrame:CGRectMake(0, 0, UIScreenWidth, kHeightScale(157))];
    //添加到视图中
    self.tableView.tableHeaderView = self.cycScrollView;
    
    _borderNum = 15.f;
    
    //Blick传值
    __block typeof(self) weakSelf = self;
    self.cycScrollView.searchPushBlock = ^(PYSearchViewController *vc) {
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    self.cycScrollView.searchPopBlock = ^(PYSearchViewController *vc) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    
    self.cycScrollView.newspushBlock = ^(BOOL isSelect) {
        [weakSelf.navigationController pushViewController:[NewsFromViewController new] animated:YES];
    };
}

#pragma mark - tableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger inter;
    if (section == 0) {
        inter = 1;
    }else if (section == 1){
        inter = 1;
    }else if (section == 2){
        inter = 3;
    }else{
        inter = _hotDebateSYModelArr.count;
    }
    return inter;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat ffloat;
    
    if (indexPath.section == 0) {
        ffloat = kHeightScale(135);
    }
    else if (indexPath.section == 1){
        ffloat = kHeightScale(192);
    }else if (indexPath.section == 2){
        if (indexPath.row == 2) {
            ffloat = kHeightScale(299.5);
        }else{
            ffloat = kHeightScale(304.5);
        }
    }else{
        HotDebateSYModel_list_comment * _model_list_comment = _hotDebateSYModelArrTwo[indexPath.row];
        
        if (![_model_list_comment.head_img isEqualToString:@""]) {
            ffloat = kHeightScale(205);
        }else
        {
            ffloat = kHeightScale(178);;
        }
    }
    
    return ffloat;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    CGFloat ffloat;
    
//    if (section == 3) {
//        ffloat = kHeightScale(30);
//    }else{
        ffloat = kHeightScale(36);
//    }
    return ffloat;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [UIView new];
    
    NSArray *arr = @[@"排行榜",@"热门预告",@"热门创想",@"热门辩论"];
    
    UIImageView *leftImg = [[UIImageView alloc] init];
    leftImg.image = [UIImage imageNamed:@"fanhui"];
    // 填充
    leftImg.contentMode = UIViewContentModeScaleAspectFit;
    [view addSubview:leftImg];
    
    UILabel * lab2 = [[UILabel alloc]init];
    lab2.textAlignment = 0;
    lab2.font = [UIFont boldSystemFontOfSize:kWidthScale(15)];
    lab2.textColor = [UIColor colorWithHexString:@"#333333"];
    lab2.text = arr[section];
    [view addSubview:lab2];
    
    lab2.sd_layout
    .centerYEqualToView(view)
    .leftSpaceToView(view, kWidthScale(15))
    .widthIs(kWidthScale(100))
    .autoHeightRatio(0);
    
    leftImg.sd_layout
    .centerYEqualToView(lab2)
    .rightSpaceToView(view,kWidthScale(15))
    .widthIs(kWidthScale(15))
    .heightIs(kHeightScale(15));
    
    view.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    
    //创建一个手势进行点击，这里可以换成button
    
    UIButton * but = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, kHeightScale(36))];
    but.tag = 300+section;
    but.backgroundColor = [UIColor clearColor];
    [but addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:but];
    
    return view;
}

-(void)click:(UIButton *)sender
{
    UIButton *btn = (UIButton *)sender;
    
//    NSString *str = [NSString stringWithFormat:@"%ld",(long)sender.tag - 300];
    
    switch (btn.tag) {
        case 300:
            [self.navigationController pushViewController:[LeaderboardFromViewController new] animated:YES];
            break;
            
        case 301:
            [self.navigationController pushViewController:[PopularForecastViewController new] animated:YES];
            break;
            
        case 302:
            [self.navigationController pushViewController:[HotBrainStormViewController new] animated:YES];
            break;
           
        case 303:
            [self.navigationController pushViewController:[HotspotdebateSYViewController new] animated:YES];
            
            break;
        default:
            break;
    }
}

- (void)clickListBtn:(NSString *)str
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"点击了%@按钮",str] message:nil delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
    [alert show];
}

#pragma mark - tableView DataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        HomeListFromTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homelist"];
        if (!cell ) {
            cell = [[HomeListFromTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"homelist"];
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
    }
    else if (indexPath.section == 1){
        _homeYuGaoCell = [tableView dequeueReusableCellWithIdentifier:@"homeyugao"];
        if (!_homeYuGaoCell ) {
            _homeYuGaoCell = [[HomeYuGaoFromTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"homeyugao"];
            _homeYuGaoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        __block typeof(self) weakSelf = self;
        _homeYuGaoCell.clickHotMeeting = ^(NSString *isClick) {
            [weakSelf.navigationController pushViewController:[DetailsOfTheMeetingFromViewController new] animated:YES];
        };
        return _homeYuGaoCell;
    }
    else if (indexPath.section == 2){
        HomeNaoBaoFormTableViewCell *stormCell = [tableView dequeueReusableCellWithIdentifier:@"homeNaoBao"];
        
        if (!stormCell) {
            stormCell = [[HomeNaoBaoFormTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"homeNaoBao"];
            stormCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
//        else{
//            while ([stormCell.imageFabiao.subviews lastObject] != nil) {
//                [(UIView*)[stormCell.imageFabiao.subviews lastObject] removeFromSuperview];  //删除并进行重新分配
//            }
//        }
        if (indexPath.row == 2) {
            stormCell.backBgColor.hidden = YES;
        }
        
        if (_stormDataSource.count) {
            stormCell.model = _stormDataSource[indexPath.row];
        }
        
        
        return stormCell;
    }
    else if (indexPath.section == 3){
        
        HomeDebateFromTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homeDebate"];
        if (!cell) {
            cell = [[HomeDebateFromTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"homeDebate"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        cell.model=_hotDebateSYModelArr[indexPath.row];
        cell.list_comment=_hotDebateSYModelArrTwo[indexPath.row];
        return cell;
    }
    
    return nil;
}
//tableViewCell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 3)
    {
        [self.navigationController pushViewController:[ParticularsViewController new] animated:YES];
    }
    else if (indexPath.section == 2)
    {
        [self.navigationController pushViewController:[HotBrainStormViewController new] animated:YES];
    }
}

#pragma mark - 设置导航
- (void)initNavigation{
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationItem.title = self.tabBarItem.title;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kHeightScale(-20), UIScreenWidth, UIScreenHeight+kHeightScale(25)) style:UITableViewStylePlain];
        
        _tableView.delegate = self;
        
        _tableView.dataSource = self;
    }
    return _tableView;
}

@end
